package com.cai.primeton.controller;

import com.cai.primeton.entity.PBook;
import com.cai.primeton.entity.PType;
import com.cai.primeton.entity.R;
import com.cai.primeton.repository.BookRepo;
import com.cai.primeton.repository.BorrowRepo;
import com.cai.primeton.repository.CategoryRepo;
import com.cai.primeton.service.BookService;
import com.cai.primeton.service.CategoryService;
import io.swagger.annotations.*;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @version 1.0
 * @author：蔡松坡
 * @date：2021/7/1 15 : 52
 * @package：com.cai.primeton.controller
 */
@Controller
@Api(tags = "图书管理模块")
public class BookController {

//    @Autowired
//    private BookRepo bookRepo;

    @Autowired
    private BookService bookService;

//    @Autowired
//    private CategoryRepo categoryRepo;

    @Autowired
    private CategoryService categoryService;



    /**
     * 添加图书
     * @param pBook
     * @return
     */
    @ApiOperation(value = "添加图书")
    @PostMapping("/book/insert")
    public @ResponseBody Map insertBook(PBook pBook){
//        bookRepo.save(pBook);
        bookService.save(pBook);
        R r = new R(200,"success");
        return r.result();
    }



    /**
     * 根据id查询图书信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询图书信息")
    @ApiImplicitParam(name = "id",value = "传入要查询图书的id")
    @GetMapping("/book/find/{id}")
    public String findBookById(@PathVariable("id") Integer id,Model model){
//        Optional<PBook> byId = bookRepo.findById(id);
        PBook byId = bookService.findById(id);
        List<PType> all = categoryService.findAll();
        model.addAttribute("pBooks",byId);
        model.addAttribute("pTypes",all);
        return "bookdetail";

    }

    /**
     * 修改图书信息
     * @param pBook
     * @return
     */
    @ApiOperation(value = "修改图书信息")
//    @ApiImplicitParam(name = "pBook",value = "要修改的图书信息，其中图书编号为必填项")
    @PutMapping("/book/update")
    public @ResponseBody Map updateBook(PBook pBook){
        if(pBook.getId()==null){
            R r = new R(333,"图书编号不能为空");
            return r.result();
        }
        bookService.save(pBook);
        R r = new R(200,"success");
        return r.result();
    }

    /**
     * 根据id 删除图书
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id 删除图书信息")
    @ApiImplicitParam(name = "id",value = "要删除图书的编号")
    @DeleteMapping("/book/delete/{id}")
    public @ResponseBody Map deleteBook(@PathVariable("id") Integer id){
        bookService.deleteById(id);
        R r = new R(200,"success");
        return r.result();
    }
}
